package com.seng.resourcetycoon.gui.views;

import com.seng.resourcetycoon.HelloApplication;
import com.seng.resourcetycoon.core.enums.TowerState;
import com.seng.resourcetycoon.gui.models.ResourceTower;
import com.seng.resourcetycoon.services.ResourceInventory;
import com.seng.resourcetycoon.util.ResourceReader;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;

import java.io.IOException;
import java.util.Objects;

public class TowerGardItemView {

    @FXML
    private VBox content;
    @FXML
    private Label name;
    @FXML
    private Label generationRate;
    @FXML
    private Label generated;
    @FXML
    private ImageView image;
    @FXML
    private Label status;
    private ResourceTower resourceTower;

    public TowerGardItemView() {
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("tower-grid.fxml"));
        fxmlLoader.setController(this);
        try {
            fxmlLoader.load();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void bindData(ResourceTower item) {
        this.resourceTower = item;
        refreshUI(item);
        try {
            Image image1 = new Image(ResourceReader.getResourceAsStream(item.getResourceType().getDescription() + ".jpg"));
            image.setImage(image1);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void refreshUI(ResourceTower item) {
        name.setText("Name：" + item.getName());
        generationRate.setText("Generation Rate: " + item.getResourceGenerationAmount() + "/" + (item.getResourceGenerationInterval()) + "s");
        generated.setText("Generated: " + item.getResourceType().getDescription() + " x0");
        status.setText("Status：" + item.getState().getDescription());
        status.setVisible(item.getState() != TowerState.ACTIVE);
    }

    public boolean refreshViewByResourceId(ResourceTower tower) {
        if (Objects.equals(tower.getId(), this.resourceTower.getId())) {
            refreshUI(tower);
            return true;
        }
        return false;
    }

    public void generateResource() {
        if (resourceTower.attemptToGenerateResources()) {
            ResourceInventory.getInstance().setResourceCount(resourceTower.getResourceType(), resourceTower.getResourceGenerationAmount());
            generated.setText("Generated: " + resourceTower.getResourceType().getDescription() + " x" + resourceTower.getCurrentResourceAmount());
        }
    }

    public Pane getContent() {
        return content;
    }
}
